from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session, joinedload
from sqlalchemy import and_, or_, func
from datetime import datetime, timedelta

from app.core.database import get_db
from app.models.user import User
from app.models.team import Team, TeamMember, TeamInvitation, TeamRole, TeamStatus
from app.models.competition import Competition
from app.schemas.team import (
    TeamCreate, TeamUpdate, TeamResponse, TeamList,
    TeamMemberResponse, TeamInvitationCreate, TeamInvitationResponse
)
from app.api.v1.endpoints.auth import get_current_active_user

router = APIRouter()


@router.post("/", response_model=TeamResponse)
async def create_team(
    team_data: TeamCreate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """创建团队"""
    # 检查竞赛是否存在
    competition = db.query(Competition).filter(Competition.id == team_data.competition_id).first()
    if not competition:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Competition not found"
        )
    
    # 检查竞赛是否允许组队
    if not competition.allow_team_formation:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Team formation not allowed for this competition"
        )
    
    # 检查用户是否已经在该竞赛中有团队
    existing_membership = db.query(TeamMember).join(Team).filter(
        and_(
            Team.competition_id == team_data.competition_id,
            TeamMember.user_id == current_user.id,
            TeamMember.status == "active"
        )
    ).first()
    
    if existing_membership:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="You are already in a team for this competition"
        )
    
    # 创建团队
    team = Team(
        name=team_data.name,
        description=team_data.description,
        competition_id=team_data.competition_id,
        leader_id=current_user.id,
        max_members=min(team_data.max_members or competition.max_team_size, competition.max_team_size),
        is_recruiting=team_data.is_recruiting,
        required_skills=team_data.required_skills,
        status=TeamStatus.ACTIVE
    )
    
    db.add(team)
    db.flush()  # 获取团队ID
    
    # 添加创建者为团队领导
    team_member = TeamMember(
        team_id=team.id,
        user_id=current_user.id,
        role=TeamRole.LEADER,
        status="active"
    )
    
    db.add(team_member)
    db.commit()
    db.refresh(team)
    
    return team


@router.get("/", response_model=List[TeamList])
async def get_teams(
    competition_id: Optional[int] = Query(None, description="竞赛ID"),
    is_recruiting: Optional[bool] = Query(None, description="是否招募中"),
    skills: Optional[List[str]] = Query(None, description="技能要求"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    db: Session = Depends(get_db)
):
    """获取团队列表"""
    query = db.query(Team).filter(Team.status == TeamStatus.ACTIVE)
    
    # 竞赛筛选
    if competition_id:
        query = query.filter(Team.competition_id == competition_id)
    
    # 招募状态筛选
    if is_recruiting is not None:
        query = query.filter(Team.is_recruiting == is_recruiting)
    
    # 技能筛选
    if skills:
        for skill in skills:
            query = query.filter(Team.required_skills.contains([skill]))
    
    # 搜索
    if search:
        search_filter = or_(
            Team.name.ilike(f"%{search}%"),
            Team.description.ilike(f"%{search}%")
        )
        query = query.filter(search_filter)
    
    # 排序：招募中的团队优先，然后按创建时间
    query = query.order_by(Team.is_recruiting.desc(), Team.created_at.desc())
    
    # 分页
    offset = (page - 1) * size
    teams = query.offset(offset).limit(size).all()
    
    return teams


@router.get("/{team_id}", response_model=TeamResponse)
async def get_team(
    team_id: int,
    db: Session = Depends(get_db)
):
    """获取团队详情"""
    team = db.query(Team).options(
        joinedload(Team.members).joinedload(TeamMember.user),
        joinedload(Team.competition),
        joinedload(Team.leader)
    ).filter(Team.id == team_id).first()
    
    if not team:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Team not found"
        )
    
    return team


@router.put("/{team_id}", response_model=TeamResponse)
async def update_team(
    team_id: int,
    team_update: TeamUpdate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """更新团队信息"""
    team = db.query(Team).filter(Team.id == team_id).first()
    if not team:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Team not found"
        )
    
    # 检查权限（只有团队领导可以更新）
    if team.leader_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only team leader can update team information"
        )
    
    # 更新团队信息
    update_data = team_update.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(team, field, value)
    
    db.commit()
    db.refresh(team)
    return team


@router.delete("/{team_id}")
async def delete_team(
    team_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """解散团队"""
    team = db.query(Team).filter(Team.id == team_id).first()
    if not team:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Team not found"
        )
    
    # 检查权限（只有团队领导可以解散）
    if team.leader_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only team leader can disband the team"
        )
    
    # 软删除团队
    team.status = TeamStatus.DISBANDED
    
    # 更新所有成员状态
    db.query(TeamMember).filter(TeamMember.team_id == team_id).update(
        {"status": "inactive"}
    )
    
    db.commit()
    return {"message": "Team disbanded successfully"}


@router.post("/{team_id}/join")
async def join_team(
    team_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """申请加入团队"""
    team = db.query(Team).filter(Team.id == team_id).first()
    if not team:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Team not found"
        )
    
    # 检查团队是否招募中
    if not team.is_recruiting:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Team is not recruiting"
        )
    
    # 检查团队是否已满
    current_members = db.query(TeamMember).filter(
        and_(
            TeamMember.team_id == team_id,
            TeamMember.status == "active"
        )
    ).count()
    
    if current_members >= team.max_members:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Team is full"
        )
    
    # 检查用户是否已经在该竞赛中有团队
    existing_membership = db.query(TeamMember).join(Team).filter(
        and_(
            Team.competition_id == team.competition_id,
            TeamMember.user_id == current_user.id,
            TeamMember.status == "active"
        )
    ).first()
    
    if existing_membership:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="You are already in a team for this competition"
        )
    
    # 检查是否已经申请过
    existing_application = db.query(TeamMember).filter(
        and_(
            TeamMember.team_id == team_id,
            TeamMember.user_id == current_user.id,
            TeamMember.status == "pending"
        )
    ).first()
    
    if existing_application:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="You have already applied to join this team"
        )
    
    # 创建申请
    team_member = TeamMember(
        team_id=team_id,
        user_id=current_user.id,
        role=TeamRole.MEMBER,
        status="pending"
    )
    
    db.add(team_member)
    db.commit()
    
    return {"message": "Application submitted successfully"}


@router.post("/{team_id}/members/{user_id}/approve")
async def approve_member(
    team_id: int,
    user_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """批准成员申请"""
    team = db.query(Team).filter(Team.id == team_id).first()
    if not team:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Team not found"
        )
    
    # 检查权限（只有团队领导可以批准）
    if team.leader_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only team leader can approve members"
        )
    
    # 查找待批准的申请
    member_application = db.query(TeamMember).filter(
        and_(
            TeamMember.team_id == team_id,
            TeamMember.user_id == user_id,
            TeamMember.status == "pending"
        )
    ).first()
    
    if not member_application:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Member application not found"
        )
    
    # 检查团队是否已满
    current_members = db.query(TeamMember).filter(
        and_(
            TeamMember.team_id == team_id,
            TeamMember.status == "active"
        )
    ).count()
    
    if current_members >= team.max_members:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Team is full"
        )
    
    # 批准申请
    member_application.status = "active"
    member_application.joined_at = datetime.utcnow()
    
    db.commit()
    
    return {"message": "Member approved successfully"}


@router.delete("/{team_id}/members/{user_id}")
async def remove_member(
    team_id: int,
    user_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """移除团队成员"""
    team = db.query(Team).filter(Team.id == team_id).first()
    if not team:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Team not found"
        )
    
    # 检查权限（团队领导可以移除任何人，成员只能移除自己）
    if team.leader_id != current_user.id and user_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Permission denied"
        )
    
    # 不能移除团队领导
    if user_id == team.leader_id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Cannot remove team leader"
        )
    
    # 查找成员
    member = db.query(TeamMember).filter(
        and_(
            TeamMember.team_id == team_id,
            TeamMember.user_id == user_id,
            TeamMember.status.in_(["active", "pending"])
        )
    ).first()
    
    if not member:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Member not found"
        )
    
    # 移除成员
    member.status = "inactive"
    member.left_at = datetime.utcnow()
    
    db.commit()
    
    return {"message": "Member removed successfully"}


@router.get("/{team_id}/members", response_model=List[TeamMemberResponse])
async def get_team_members(
    team_id: int,
    db: Session = Depends(get_db)
):
    """获取团队成员列表"""
    team = db.query(Team).filter(Team.id == team_id).first()
    if not team:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Team not found"
        )
    
    members = db.query(TeamMember).options(
        joinedload(TeamMember.user)
    ).filter(
        and_(
            TeamMember.team_id == team_id,
            TeamMember.status.in_(["active", "pending"])
        )
    ).all()
    
    return members